﻿using System;
using System.Collections;
using System.Web.Mvc;
using System.Diagnostics;
using Super.Common;

namespace Super.Filter
{
    public class BKActionFilter : FilterAttribute, IActionFilter, IResultFilter
    {
        private const string ProcessTimerKey = "BangKe.ProcessTimer";


        public BKActionFilter()
        {
            IsNotResponse = true;
        }

        /// <summary> 是否不输出信息.
        /// </summary>
        public bool IsNotResponse { get; set; }


        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var processTimer = new Stopwatch();
            processTimer.Start();


            //HttpContext.Current.Items["QueryCount"] = 0;

            // filterContext.HttpContext.Items["Rich.Wong.ProcessTimer"] = processTimer; //上下文

            filterContext.Controller.ViewData[ProcessTimerKey] = processTimer;
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Controller.ViewData[ProcessTimerKey] != null)
            {
                filterContext.Controller.ViewData["BangKe.ActionProcess"] = ((Stopwatch)filterContext.Controller.ViewData[ProcessTimerKey]).Elapsed.TotalMilliseconds;
            }
        }

        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (DataCache.HttpContextCache["FirstValidate"] != null)
            {
                //禁止回退
                //每十分钟心跳一下.....- -# 并且检验是否合法.
                filterContext.HttpContext.Response.Write("<script type='text/javascript'> setInterval(function () { $.get('/_command?cmd=ValidatePant'); }, 1000 * 60 * 10);</script>");
            }

            //信息输出
            filterContext.HttpContext.Response.Write(filterContext.Controller.ViewBag.PageShowMessages);


            //filterContext.HttpContext.Response.Write(string.Format("<center><span class=\"timer\" style=\"font-size:8px;color:#666\">view:{0}ms, action:{1}ms, query:{2}</span></center>",
            //    filterContext.Controller.ViewData["BangKe.ViewProcess"],
            //    filterContext.Controller.ViewData["BangKe.ActionProcess"],
            //    filterContext.Controller.ViewData["BangKe.SqlCount"]));
        }

        public void OnResultExecuting(ResultExecutingContext filterContext)
        {

            //view页面数据传送之前
        }
    }

   
}
